//
//  YTTimeButton.m
//  倒计时按钮
//
//  Created by lyt on 16/11/18.
//  Copyright © 2016年 com.dazhebao. All rights reserved.
//

#import "YTTimeButton.h"

@implementation YTTimeButton

- (instancetype)init{
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)beginTime:(NSInteger)time title:(NSString *)title sendingColor:(UIColor *)sColor finishColor:(UIColor *)fColor{
    __block NSInteger time1 = time -1;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    // 创建一个定时器
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 60 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        
        if (time1 <= 0) {
            
            dispatch_source_cancel(timer);//取消定时器
            // 时间结束处理
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setTitle:title forState:UIControlStateNormal];
                [self setTitleColor:fColor forState:UIControlStateNormal];
                self.userInteractionEnabled = YES;
            });
        }else{
            // 倒计时处理
            int seconds = time1 % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self setTitle:[NSString stringWithFormat:@"%.2d%@",seconds,title] forState:UIControlStateNormal];
                [self setTitleColor:sColor forState:UIControlStateNormal];
                self.userInteractionEnabled = NO;
            });
            time1--;
        }
    });
    dispatch_resume(timer);
    
}
@end
